package cn.kgc.bdqn_studentinfomanager.service.UserService.impl;

import cn.kgc.bdqn_studentinfomanager.dao.user.UserMapper;
import cn.kgc.bdqn_studentinfomanager.pojo.Model.BdqnTeacherinfo;
import cn.kgc.bdqn_studentinfomanager.pojo.common.Const;
import cn.kgc.bdqn_studentinfomanager.pojo.common.ResponseCode;
import cn.kgc.bdqn_studentinfomanager.pojo.common.ServerResponse;
import cn.kgc.bdqn_studentinfomanager.pojo.vo.BdqnTokepVo;
import cn.kgc.bdqn_studentinfomanager.pojo.vo.ShowRoleVo;
import cn.kgc.bdqn_studentinfomanager.pojo.vo.StateVo;
import cn.kgc.bdqn_studentinfomanager.pojo.vo.FromData;
import cn.kgc.bdqn_studentinfomanager.service.UserService.UserService;
import cn.kgc.bdqn_studentinfomanager.service.UserService.TokenService;
import cn.kgc.bdqn_studentinfomanager.utils.MD5Util;
import cn.kgc.bdqn_studentinfomanager.utils.RedisUtil;
import cn.kgc.bdqn_studentinfomanager.utils.SMSSendUtil;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * by Shanshui CC on 2020/12/6 13:28
 */
@Service("userService")
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private TokenService tokenService;

    /**
     * 登录
     *
     * @param phone
     * @param userPassowrd
     * @return
     */
    @Override
    public ServerResponse queryTeacherInfo(String phone, String userPassowrd, String userAgent) {
        if (StringUtils.isBlank(phone) || StringUtils.isBlank(userPassowrd)) {
            return ServerResponse.createByErrorMessage("用户参数错误");
        }


        String returnPhone = userMapper.queryPhone(phone);

        if(returnPhone == null){
            return ServerResponse.createByErrorMessage("手机号不存在");
        }
        String MD5Password = MD5Util.MD5EncodeUtf8(userPassowrd);

        System.out.println("加密过后密码的是:"+MD5Password);
        BdqnTeacherinfo bdqnTeacherinfo = userMapper.queryTeacherInfo(phone, MD5Password);
        if (bdqnTeacherinfo == null) {
            return ServerResponse.createByErrorMessage("密码错误");
        }

        //如果当前账户还有Token 就删除
        if (!StringUtils.isBlank(redisUtil.getStr(bdqnTeacherinfo.getId().toString()))) {
            redisUtil.del(redisUtil.getStr(bdqnTeacherinfo.getId().toString()));
            System.out.println("........ 删除完成。。。。。。。 删除的键为： " + bdqnTeacherinfo.getId().toString());
        }

        //TODO token的生成
        String token = tokenService.generatorToken(userAgent, bdqnTeacherinfo);
        //为防止重复登录生成多个Token
        redisUtil.setStr(bdqnTeacherinfo.getId().toString(), token);

        System.out.println("当前Id是:" + bdqnTeacherinfo.getId());

        //TODO token的存储
        redisUtil.setStr(token, JSONObject.toJSONString(bdqnTeacherinfo), (long) Const.RedisConst.SESSION_TIMEOUT);

        //组装 Vo
        BdqnTokepVo bdqnTokenVo = new BdqnTokepVo();
        bdqnTokenVo.setGenTime(System.currentTimeMillis());
        bdqnTokenVo.setExpTime(System.currentTimeMillis() + Const.RedisConst.SESSION_TIMEOUT * 1000);
        bdqnTokenVo.setToken(token);

        return ServerResponse.createBySuccess(bdqnTokenVo);

    }


    /**
     * 获取短信方法
     *
     * @param phone
     */
    @Override
    public void get_PhoneCode(String phone) {
        //手机注册
        int num = (int) (Math.random() * 8999) + 1000;
        String[] str = {num + "", "5"};     //这个5是五分钟的意思
        SMSSendUtil.sendSms(phone, "1", str);   //这个 1 是使用第一套模板的意思
        System.out.println(num);
        redisUtil.setStr(phone, num + "", (long) 5 * 60);
        System.out.println(redisUtil.getStr(phone));
    }


    /**
     * 校验验证码
     *
     * @param phone
     * @param code
     * @return
     */
    @Override
    public int checkPhoneCode(String phone, String code) {
        //验证码一致
        if (redisUtil.getStr(phone).equals(code)) {
            return 1;
        }
        //验证码不一致
        return 0;
    }

    /**
     * 点击注册页面时加载专员下拉框
     * @return
     */
    @Override
    public ServerResponse showCommissioner() {
        List<ShowRoleVo> showRoleVoList = userMapper.showCommissioner();
        //遍历电话号码  将中间四位变为 *
        for (ShowRoleVo showRoleVos : showRoleVoList) {
            String phone = showRoleVos.getPhone();
            showRoleVos.setPhone(phone.substring(0, 3) + "****" + phone.substring(7, phone.length()));
            //将名字中间的那个字biancheng *
            if (showRoleVos.getUserName().length() >= 3) {
                showRoleVos.setUserName(
                        showRoleVos.getUserName()
                                .substring(0, 1) + "*" +
                                showRoleVos.getUserName().substring(
                                        2, showRoleVos.getUserName().length()));
            }

        }
        return ServerResponse.createBySuccess(showRoleVoList);
    }

    /**
     *  展示角色
     *  登录时选择角色的下拉框
     * @return
     */
    @Override
    public ServerResponse role() {
        /**
         * 查询所有职位列表
         */
        List<StateVo> stateVoList = userMapper.queryStateName();
        if(stateVoList == null){
            return ServerResponse.createByErrorMessage("查询角色失败");
        }
        return ServerResponse.createBySuccess(stateVoList);
    }

    /**
     * 手机号注册
     *
     * @param fromData
     * @return
     */
    @Override
    public ServerResponse register(FromData fromData) {
        if (fromData == null) {
            return ServerResponse.createByErrorMessage("用户信息丢失，无法完成注册");
        }
        /**
         * 查询专员手机号是否存在     存在则返回id
         */
        System.out.println("开始查专员老师");
        Integer commId = userMapper.queryCommissionerByPhone(fromData.getCommissioner());
        System.out.println("专员老师Id为:"+commId);

        if(commId == null){
            return ServerResponse.createByErrorMessage("手机号不存在");
        }
        //将渠道专员Id传入对象
        fromData.setParentId(commId);
        //调用方法判断前端传来的手机验证码 与 Redis里的是否一致
        if (checkPhoneCode(fromData.getPhone(), fromData.getPhoneCode()) == 1) {
            //添加成功02
            fromData.setPassword(MD5Util.MD5EncodeUtf8(fromData.getPassword()));

            System.out.println("from加密过后的密码是:"+ fromData.getPassword());

            Integer integer = userMapper.insertTeacherInfo(fromData);
            if (integer > 0) {
                return ServerResponse.createBySuccessMessage("恭喜你，注册成功");
            }
        } else {
            //验证码不正确
            return ServerResponse.createByErrorMessage("验证不存在");
        }
        System.out.println("失败了");
        //专员手机号不匹配
        //CommError
        return ServerResponse.createByErrorMessage(ResponseCode.ILLEGAL_ARGUMENT.getDesc());
    }


//    /**
//     * 通过手机号找回密码
//     * @param phone
//     * @return
//     */
//    @Override
//    public ServerResponse retrieveByPhone(String phone,String phoneCode) {
//        if(StringUtils.isBlank(phone)){
//            return ServerResponse.createByErrorMessage("手机不能为空");
//        }
//        if(phoneCode.equals(redisUtil.getStr(phone))){
//
//        }
//
//    }


    /**
     * 短信登录
     *
     * @param phone
     * @param phoneCode
     * @return
     */
    @Override
    public ServerResponse phoneCodeLogin(String phone, String phoneCode) {
        if (StringUtils.isBlank(phone) || StringUtils.isBlank(phoneCode)) {
            return ServerResponse.createByErrorMessage("参数丢失");
        }
        if (redisUtil.getStr(phone).equals(phoneCode)) {
            BdqnTeacherinfo bdqnTeacherinfo = userMapper.queryTeacherInfoByPhone(phone);
            if (bdqnTeacherinfo != null) {
                return ServerResponse.createBySuccess(bdqnTeacherinfo);
            } else {
                return ServerResponse.createByErrorMessage("登陆失败  ");
            }
        } else {
            return ServerResponse.createByErrorMessage("验证码错误");
        }
    }

    /**
     * 修改用户密码
     *
     * @param userPassword
     * @param token
     * @return
     */
    @Override
    public ServerResponse updateTeacherInfoUserPassword(String userPassword,
                                                        String newUserPassword,
                                                        String token) {
        //判空
        if (StringUtils.isBlank(userPassword)) {
            return ServerResponse.createByErrorMessage("请输入原密码");
        }
        //从token中拿到用户id
        String id = org.apache.commons.lang3.StringUtils.substring(
                token, token.indexOf(":") + 1, token.indexOf("-"));
        //根据id查询用户信息


        BdqnTeacherinfo bdqnTeacherinfo = userMapper.queryTeacherInfoById(id);

        String MD5Password = MD5Util.MD5EncodeUtf8(userPassword);

        System.out.println("MD5Passowrd是:" + MD5Password);
        System.out.println("UserPassword是:" + bdqnTeacherinfo.getUserpassword());

        //判断用户密码与传过来的密码是否一致
        if (!bdqnTeacherinfo.getUserpassword().equals(MD5Password)) {
            return ServerResponse.createByErrorMessage("密码错误，请重新输入原密码");
        }
        //调用方法修改密码
        String NewMD5Password = MD5Util.MD5EncodeUtf8(newUserPassword);
        Integer integer = userMapper.updateTechaerInfoUserPassword(NewMD5Password, id);
        if (integer == 1) {
            return ServerResponse.createBySuccessMessage("密码修改成功！");
        }
        return ServerResponse.createByErrorMessage("密码修改失败");
    }

    /**
     * 忘记密码
     * @param phone
     * @param phoneCode
     * @return
     */
    @Override
    public ServerResponse forgetPwd(String phone, String phoneCode,String newPassword) {
        if(StringUtils.isBlank(phone)){
            return ServerResponse.createByErrorMessage("参数不能为空");
        }
        if(redisUtil.getStr(phone).equals(phoneCode)){
            Integer integer = userMapper.updatePwd(phone, newPassword);
            if(integer >= 1){
                return ServerResponse.createBySuccessMessage("修改密码成功");
            }else {
                return ServerResponse.createByErrorMessage("修改密码失败");
            }
        }

        return ServerResponse.createByErrorMessage(ResponseCode.ILLEGAL_ARGUMENT.getDesc());
    }

}
